# Copyright 2025 Fluently AI, Inc. DBA Gabber. All rights reserved.
# SPDX-License-Identifier: SUL-1.0

import asyncio
import logging
from typing import cast

from core import node, pad
from core.node import NodeMetadata


class Json(node.Node):
    @classmethod
    def get_description(cls) -> str:
        return "Stores and manages Json object values"

    @classmethod
    def get_metadata(cls) -> NodeMetadata:
        return NodeMetadata(primary="core", secondary="primitive", tags=["json"])

    def resolve_pads(self):
        emit = cast(pad.StatelessSinkPad | None, self.get_pad("emit"))
        if not emit:
            emit = pad.StatelessSinkPad(
                id="emit",
                owner_node=self,
                group="emit",
                default_type_constraints=[pad.types.Trigger()],
            )

        value = cast(pad.PropertySourcePad | None, self.get_pad("value"))
        if not value:
            value = pad.PropertySourcePad(
                id="value",
                group="value",
                owner_node=self,
                default_type_constraints=[pad.types.Object()],
                value="",
            )

        self.pads = [emit, value]

    async def run(self):
        emit = cast(pad.StatelessSinkPad, self.get_pad_required("emit"))
        value = cast(pad.PropertySourcePad, self.get_pad_required("value"))

        async def emit_task():
            async for item in emit:
                value.push_item(value.get_value(), item.ctx)
                item.ctx.complete()

        await asyncio.gather(emit_task())
